//
//  DCMyProductionViewController.m
//  HNBaseProject
//
//  Created by cc on 2024/7/19.
//

#import "DCMyProductionViewController.h"
#import "DCProductionListViewController.h"
#import "DCProductionDetailViewController.h"
#import "AIChargeListController.h"
#import "AIKefuView.h"
#import "YNSSetController.h"
#import "DCMyProductionHistoryCell.h"
#import "YNSPayVC.h"
#import "AIMyHistoryCreateModel.h"
#import "YNSResultVC.h"
@interface DCMyProductionViewController () <UICollectionViewDataSource, UICollectionViewDelegate,MxNavigationViewDelegate>
@property (nonatomic, strong) MxPublicNav *nav;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UILabel *userNameL;
@property (weak, nonatomic) IBOutlet UIImageView *headIcon;
@property (weak, nonatomic) IBOutlet UILabel *noticeLab;
@property (nonatomic, strong) UILabel *nameLab;
@property (weak, nonatomic) IBOutlet UIView *topBg;
@property (weak, nonatomic) IBOutlet UIScrollView *bgScroll;
@property (weak, nonatomic) IBOutlet UIView *historyBg;
@property (nonatomic, strong) UIView *nodataV;
@property (weak, nonatomic) IBOutlet UILabel *moneyLab;
@property (nonatomic, strong) NSMutableArray *listArray;

@property (weak, nonatomic) IBOutlet UILabel *diamodCoutLab;

@property (weak, nonatomic) IBOutlet UILabel *mineDiamo;

@property (weak, nonatomic) IBOutlet UIButton *rechargeBtn;

@property (weak, nonatomic) IBOutlet UILabel *myToolsLab;

@property (weak, nonatomic) IBOutlet UILabel *rechageRdLab;

@property (weak, nonatomic) IBOutlet UILabel *costrdLab;

@property (weak, nonatomic) IBOutlet UILabel *contantLab;

@property (weak, nonatomic) IBOutlet UILabel *setLab;


@property (weak, nonatomic) IBOutlet UILabel *histouryLab;


@property (weak, nonatomic) IBOutlet UIButton *seeMoreLab;

@end

@implementation DCMyProductionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.nav = [[MxPublicNav alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kNavBarHeight)];
    self.nav.titleLab.text = NSLocalizedString(@"我的制作", nil) ;
    self.nav.delegate = self;
    [self.view addSubview:self.nav];
    [self.bgScroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.offset(kNavBarHeight);
    }];
    self.noticeLab.hidden = YES;
    self.userNameL.hidden = YES;
    
    self.diamodCoutLab.text = NSLocalizedString(@"钻石数量", nil);
    self.mineDiamo.text = NSLocalizedString(@"我的钻石", nil);
    [self.rechargeBtn setTitle:NSLocalizedString(@"充值", nil) forState:0];
    self.myToolsLab.text = NSLocalizedString(@"我的工具", nil);
    self.rechageRdLab.text = NSLocalizedString(@"充值记录", nil);
    self.costrdLab.text =  NSLocalizedString(@"消费记录", nil);
    self.contantLab.text =  NSLocalizedString(@"联系我们", nil);
    self.setLab.text = NSLocalizedString(@"设置", nil);
    self.histouryLab.text = NSLocalizedString(@"历史制作", nil);
    [self.seeMoreLab setTitle:NSLocalizedString(@"查看更多 >", nil) forState:0];
    
    [self.collectionView registerClass:[DCMyProductionHistoryCell class] forCellWithReuseIdentifier:@"DCMyProductionHistoryCell"];
    self.listArray = [[NSMutableArray alloc] init];
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    
    flowLayout.minimumLineSpacing = 13;
    flowLayout.minimumInteritemSpacing = 13;
    
    CGFloat width = (kScreenW - 2*15 - 13) / 2.;
    flowLayout.itemSize = CGSizeMake(width, 244);
    
    self.nameLab = [[UILabel alloc] init];
    self.nameLab.font = PFRFontSemibold(18);
    self.nameLab.textColor = [UIColor colorWithHexString:@"#000000"];
    self.nameLab.text =  NSLocalizedString(@"> 点此登录", nil);//@"";
    [self.topBg addSubview:self.nameLab];
    [self.nameLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.headIcon.mas_right).offset(15);
        make.centerY.mas_equalTo(self.headIcon);
    }];
    
    AIUserInfoModel *model = [RQCacheTool getCurrentUserInfo];
    if (model.token.length > 0) {
        [self.headIcon sd_setImageWithURL:[NSURL URLWithString:model.avatar]];
        self.nameLab.text = model.nickname;
//        self.moneyLab.text = model.user_money;
        [self getMoney];
        [self getHistoryList];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadMony) name:@"buysuccess" object:nil];
    
    self.collectionView.hidden = YES;//要处理
    [self.bgScroll addSubview:self.nodataV];
    [self.nodataV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.mas_equalTo(80);
        make.top.mas_equalTo(self.historyBg.mas_bottom).offset(20);
    }];
}

- (void)getHistoryList {

    MJWeakSelf
    [[DCHttpClient shareClient] requestWithPath:@"api/video.video/historyVideo" params:@{@"state":@(2)} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if([dict[@"code"] intValue]==1){
            [weakSelf.listArray removeAllObjects];
            NSArray *dataArray = [NSArray modelArrayWithClass:[AIMyHistoryCreateModel class] json:dict[@"data"][@"lists"]];
            [weakSelf.listArray addObjectsFromArray:dataArray];
            if (weakSelf.listArray.count >0) {
                weakSelf.collectionView.hidden = NO;
                weakSelf.nodataV.hidden = YES;
            } else {
                weakSelf.collectionView.hidden = YES;
                weakSelf.nodataV.hidden = NO;
            }
            [weakSelf.collectionView reloadData];
        } else {

        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (void)reloadMony {
    [self getMoney];
}

- (void)getMoney {
    MJWeakSelf
    [[DCHttpClient shareClient] requestWithPath:@"api/user/center" params:@{} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if([dict[@"code"] intValue]==1){
            NSString *user_money = [NSString stringWithFormat:@"%@",dict[@"data"][@"user_money"]];
            weakSelf.moneyLab.text = user_money;
        } else {

        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (void)leftTap {
    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)loginButtonClick:(id)sender {
    AIUserInfoModel *model = [RQCacheTool getCurrentUserInfo];
    if (model.ID.length >0) {
        return;
    }
    [self loginClick];
}

- (void)loginClick {
    [self.view makeToastActivity];
    UIDevice *device = [UIDevice currentDevice];//创建设备对象
    NSString *deviceUID = [[NSString alloc] initWithString:device.identifierForVendor.UUIDString];
    MJWeakSelf
    NSDictionary *dict = @{@"udid" : deviceUID};
    [[DCHttpClient shareClient] requestWithPath:@"api/login/uDidBind" params:dict httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        if([dict[@"code"] intValue]==1){
            [weakSelf getUserInfoWithId:dict[@"data"][@"udid"]];
        }
        else {
            [weakSelf.view hideToastActivity];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}



- (void)getUserInfoWithId:(NSString *)uuid {
    MJWeakSelf
    [[DCHttpClient shareClient] requestWithPath:@"api/login/udidLogin" params:@{@"udid":uuid} httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if([dict[@"code"] intValue]==1){
            AIUserInfoModel *model = [AIUserInfoModel modelWithDictionary:dict[@"data"]];
            [DCObjectManager dc_saveUserData:[NSString stringWithFormat:@"%@",model.token] forKey:DC_Token_Key];
            [weakSelf reloadViewWithModel:model];
            [weakSelf getUserInfoWithModel:model];
        } else {

        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (void)getUserInfoWithModel:(AIUserInfoModel *)model {

    MJWeakSelf
    [[DCHttpClient shareClient] requestWithPath:@"api/user/center" params:@{} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if([dict[@"code"] intValue]==1){
            NSString *user_money = [NSString stringWithFormat:@"%@",dict[@"data"][@"user_money"]];
            weakSelf.moneyLab.text = user_money;
            model.user_money = user_money;
            [RQCacheTool saveUserInfo:model];
        } else {

        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

//刷新界面
- (void)reloadViewWithModel:(AIUserInfoModel *)model {
    
    [self.headIcon sd_setImageWithURL:[NSURL URLWithString:model.avatar]];
    self.nameLab.text = model.nickname;
}
//点击充值
- (IBAction)topupButtonClick:(id)sender {
    AIUserInfoModel *model = [RQCacheTool getCurrentUserInfo];
    if (model.token.length >0) {
        YNSPayVC *payVc = [[YNSPayVC alloc] init];
        [self.navigationController pushViewController:payVc animated:YES];
    } else {
        [self loginClick];
    }

}



- (IBAction)rechargeRecordButtonClick:(id)sender {
//    @property (nonatomic, copy) NSString *type;//收支类型1:收入(充值列表传1) 2:支出(消费记录传2)
//    @property (nonatomic, copy) NSString *pay_status;//支付状态 充值列表传 2 消费记录传0
    AIUserInfoModel *model = [RQCacheTool getCurrentUserInfo];
    if (model.token.length >0) {
        AIChargeListController *chargeVc = [[AIChargeListController alloc] init];
        chargeVc.type = @"1";
        chargeVc.pay_status = @"2";
        [self.navigationController pushViewController:chargeVc animated:YES];
    } else {
        [self loginClick];
    }

}

- (IBAction)expenseCalendarButtonClick:(id)sender {
    
    AIUserInfoModel *model = [RQCacheTool getCurrentUserInfo];
    if (model.token.length >0) {
        AIChargeListController *chargeVc = [[AIChargeListController alloc] init];
        chargeVc.fromCost = YES;
        chargeVc.type = @"2";
        chargeVc.pay_status = @"0";
        [self.navigationController pushViewController:chargeVc animated:YES];
    } else {
        [self loginClick];
    }

}

- (IBAction)contactButtonClick:(id)sender {
    

    AIKefuView *view = [[AIKefuView alloc] init];
    zhPopupController *_zh_popupController = [[zhPopupController alloc] initWithView:view size:view.bounds.size];
    _zh_popupController.presentationStyle = zhPopupSlideStyleTransform;
    _zh_popupController.layoutType = zhPopupLayoutTypeCenter;
    _zh_popupController.dismissOnMaskTouched = YES;
    [_zh_popupController showInView:self.view.window duration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut bounced:NO completion:nil];
    view.cancleClick = ^{
        [_zh_popupController dismiss];
    };

    view.sureClick = ^(NSString * _Nonnull phone) {
        [_zh_popupController dismiss];
        if (phone.length>0) {
            [[DCHelpTool shareClient] dc_callMobile:phone];
        }
    };
}

- (IBAction)settingButtonClick:(id)sender {
    
    YNSSetController *setVc = [[YNSSetController alloc] init];
    [self.navigationController pushViewController:setVc animated:YES];
}

- (IBAction)lookMoreButtonClick:(id)sender {
    
    DCProductionListViewController *vc = [[DCProductionListViewController alloc] init];
    
    [self.navigationController pushViewController:vc animated:YES];
}



#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.listArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    AIMyHistoryCreateModel *model = self.listArray[indexPath.item];
    DCMyProductionHistoryCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DCMyProductionHistoryCell" forIndexPath:indexPath];
    [cell realodCellWithModel:model];
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
//    DCProductionDetailViewController *vc = [[DCProductionDetailViewController alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
    AIMyHistoryCreateModel *model = self.listArray[indexPath.item];
    MJWeakSelf
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:@"api/video.video/detail" params:@{@"id":model.ID} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if([dict[@"code"] intValue]==1){

            YNSResultVC *resultVc = [[YNSResultVC alloc] init];
            resultVc.fromList = YES;
            resultVc.video_url = dict[@"data"][@"video_url"];
            resultVc.cover_image_url = dict[@"data"][@"image_url"];
            [weakSelf.navigationController pushViewController:resultVc animated:YES];
        } else {

        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (UIView *)nodataV {
    if (!_nodataV) {
        _nodataV = [[UIView alloc] init];
        UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"history_nodata"]];
        [_nodataV addSubview:icon];
        [icon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(_nodataV);
            make.top.offset(0);
        }];
        
        UILabel *lab = [[UILabel alloc] init];
        lab.text = NSLocalizedString(@"暂无信息", nil);
        lab.font = PFRFont(12);
        lab.textColor = [UIColor colorWithHexString:@"#B7B7B7"];
        [_nodataV addSubview:lab];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(_nodataV);
            make.top.mas_equalTo(icon.mas_bottom).offset(11);
        }];
    }
    return _nodataV;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
